package com.example.demo.security.jwt;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * token的校验
 * 该类继承自BasicAuthenticationFilter，在doFilterInternal方法中，
 * 从http头的Authorization 项读取token数据，然后用Jwts包提供的方法校验token的合法性。
 * 如果校验通过，就认为这是一个取得授权的合法请求
 */
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {

    private Logger logger= LoggerFactory.getLogger(JWTAuthenticationFilter.class);

    private JWTUtils jwtUtils=new JWTUtils();


    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");

        if (header == null ) {
            chain.doFilter(request, response);
            return;
        }

        logger.info("header ",header);
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);

    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        logger.info("username", request.getParameter("username"));
        String token = request.getHeader("Authorization");
        logger.info("token " + token);

        if (token != null) {
            String username = jwtUtils.getUsername(token);
            if (username != null) {
                logger.info("auth user is " + username);
                String role = jwtUtils.getUserRole(token);
                logger.info("role is " + role);
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                String[] authoritiesStr = role.split(" ");
                for (String authority : authoritiesStr) {
                    logger.info("autoritiesStr " + authority);
                    authorities.add(new SimpleGrantedAuthority(authority));
                }

                return new UsernamePasswordAuthenticationToken(username, null, authorities);

            }
            return null;
        }

        return null;
    }

}